package com.yboot.module.quartz.service.impl;

import com.yboot.module.business.common.constant.ScheduleConstants;
import com.yboot.module.business.common.exception.job.TaskException;
import com.yboot.module.quartz.model.dto.SysJobDto;
import com.yboot.module.quartz.model.vo.SysJobVo;
import com.yboot.module.quartz.model.vo.SysJobDetailVo;
import com.yboot.module.quartz.model.query.SysJobQuery;
import com.yboot.module.quartz.model.entity.SysJobEntity;
import com.yboot.module.quartz.service.ISysJobService;
import com.yboot.module.quartz.mapper.SysJobMapper;
import com.yboot.module.quartz.util.CronUtils;
import com.yboot.module.quartz.util.ScheduleUtils;
import com.yboot.starter.mybatis.core.base.service.BaseServiceImpl;
import org.quartz.JobDataMap;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.List;

/**
 * 定时任务调度表
 *
 * @author yangcs
 * @date 2025-08-29
 */
@Service
public class SysJobServiceImpl extends BaseServiceImpl<SysJobMapper, SysJobEntity, SysJobVo, SysJobDetailVo, SysJobQuery, SysJobDto> implements ISysJobService {

    @Autowired
    private Scheduler scheduler;

    @Autowired
    private SysJobMapper jobMapper;

    /**
     * 项目启动时，初始化定时器 主要是防止手动修改数据库导致未同步到定时任务处理（注：不能手动修改数据库ID和任务组名，否则会导致脏数据）
     */
    @PostConstruct
    public void init() throws SchedulerException, TaskException {
        scheduler.clear();
        List<SysJobEntity> jobList = list();
        for (SysJobEntity job : jobList) {
            ScheduleUtils.createScheduleJob(scheduler, job);
        }
    }


    /**
     * 暂停任务
     *
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean pauseJob(String jobId) throws SchedulerException {
        SysJobEntity job = getById(jobId);
        job.setStatus(ScheduleConstants.Status.PAUSE.getValue());
        boolean result = updateById(job);
        if (result) {
            scheduler.pauseJob(ScheduleUtils.getJobKey(jobId, job.getJobGroup()));
        }
        return result;
    }

    /**
     * 恢复任务
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean resumeJob(String jobId) throws SchedulerException {
        SysJobEntity job = getById(jobId);
        job.setStatus(ScheduleConstants.Status.NORMAL.getValue());
        boolean result = updateById(job);
        if (result) {
            scheduler.resumeJob(ScheduleUtils.getJobKey(jobId, job.getJobGroup()));
        }
        return result;
    }

    /**
     * 删除后操作
     */
    public void afterDelete(List<String> ids, List<SysJobEntity> list) {
        for (SysJobEntity sysJob : list) {
            try {
                scheduler.deleteJob(ScheduleUtils.getJobKey(sysJob.getId(), sysJob.getJobGroup()));
            } catch (SchedulerException e) {
                throw new RuntimeException(e);
            }
        }
    }

    /**
     * 任务调度状态修改
     *
     * @param job 调度信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean changeStatus(SysJobEntity job) throws SchedulerException {
        boolean rows = false;
        String status = job.getStatus();
        if (ScheduleConstants.Status.NORMAL.getValue().equals(status)) {
            rows = resumeJob(job.getId());
        } else if (ScheduleConstants.Status.PAUSE.getValue().equals(status)) {
            rows = pauseJob(job.getId());
        }
        return rows;
    }

    /**
     * 立即运行任务
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean run(String jobId) throws SchedulerException {
        boolean result = false;
        SysJobEntity properties = getById(jobId);
        // 参数
        JobDataMap dataMap = new JobDataMap();
        dataMap.put(ScheduleConstants.TASK_PROPERTIES, properties);
        JobKey jobKey = ScheduleUtils.getJobKey(jobId, properties.getJobGroup());
        if (scheduler.checkExists(jobKey)) {
            result = true;
            scheduler.triggerJob(jobKey, dataMap);
        }
        return result;
    }

    /**
     * 新增任务
     */
    public void afterCreate(SysJobDto dto, SysJobEntity entity) {
        try {
            ScheduleUtils.createScheduleJob(scheduler, entity);
        } catch (SchedulerException e) {
            throw new RuntimeException(e);
        } catch (TaskException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 更新任务
     *
     */
    public void afterUpdate(SysJobDto dto, SysJobEntity job) {
        // 判断是否存在
        JobKey jobKey = ScheduleUtils.getJobKey(job.getId(), job.getJobGroup());
        try {
            if (scheduler.checkExists(jobKey)) {
                // 防止创建时存在数据问题 先移除，然后在执行创建操作
                scheduler.deleteJob(jobKey);
            }
            ScheduleUtils.createScheduleJob(scheduler, job);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * 校验cron表达式是否有效
     *
     * @param cronExpression 表达式
     * @return 结果
     */
    @Override
    public boolean checkCronExpressionIsValid(String cronExpression) {
        return CronUtils.isValid(cronExpression);
    }

}
